﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.IO.Compression;

namespace com.tiyma.httpmoudle
{
    public class CompressModule : IHttpModule
    {
        void IHttpModule.Dispose()
        {

        }

        void IHttpModule.Init(HttpApplication context)
        {

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {

            HttpApplication t_app = (HttpApplication)sender;

            bool t_sup_gzip = false;

            string t_accept_encoding = HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_ENCODING"];

            t_sup_gzip = t_accept_encoding != null && t_accept_encoding != string.Empty && t_accept_encoding.ToLower().Contains("gzip");

            string t_url = HttpContext.Current.Request.Url.ToString().ToLower();

            if (HttpContext.Current.Response.ContentType.ToLower() != "text/html" || !t_sup_gzip)
            {
                return;
            }

            if (t_url.EndsWith("/") == false)
                return;

            //ajax页面不考虑压缩
            if (t_url.Contains("/ajax")) return;

            Stream t_base_stream = t_app.Response.Filter;

            if (t_sup_gzip)
            {
                t_app.Response.Filter = new GZipStream(t_base_stream, CompressionMode.Compress);
                t_app.Response.AppendHeader("Content-Encoding", "gzip");
            }
        }

        void context_EndRequest(object sender, EventArgs e)
        {
          
            
        }
          
    }
}
